package com.guoyh.baseutils.utils

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonParser
import com.guoyh.baseutils.mylog.Loger
import com.guoyh.baseutils.factory.GsonFactory
import java.lang.reflect.Type
import java.util.*

object GsonUtil {
    private val gsonObject: Gson
        private get() = GsonFactory.getSingletonGson()

    /**
     * 对象转Gson字符串
     *
     * @param object
     * @return
     */
    fun <T : Any?> toJson(`object`: T): String {
        val gson = gsonObject
        return gson.toJson(`object`)
    }

    /**
     * Gson字符串转可序列化对象
     *
     * @param str
     * @param clazz
     * @return
     */
    fun <T> jsonToResult(str: String?, clazz: Class<T>?): T? {
        val gson = gsonObject
        var result: T? = null
        try {
            result = gson.fromJson(str, clazz)
        } catch (e: Exception) {
            Loger.dd(e.message)
            result = null
            e.printStackTrace()
        }
        return result
    }

    /**
     * Gson字符串转可序列化对象
     *
     * @param object
     * @return
     */
    fun <T : Any?> jsonToResult(`object`: String?, type: Type?): T? {
        val gson = gsonObject
        var result: T? = null
        try {
            result = gson.fromJson(`object`, type)
        } catch (e: Exception) {
            result = null
            e.printStackTrace()
        }
        return result
    }

    fun <T : Any?> deserBequiet(`object`: String?, clazz: Class<T>?): T? {
        val gson = gsonObject
        val result: T?
        result = try {
            gson.fromJson(`object`, clazz)
        } catch (e: Exception) {
            null
        }
        return result
    }

    fun <T> json2Result(class1: Class<T>, s: String): T? {
        val result: T?
        val gson = gsonObject

        result = try {
            gson.fromJson(s, class1)
        } catch (e: Exception) {
            try {
                Loger.ee(e.message)
                gson.fromJson(toJson(s), class1)
            } catch (e1: Exception) {
                Loger.ee(e1.message)
                null
            }
        }
        return result
    }

    fun <T> jsonToArray(classz: Class<T>, s: String?): MutableList<T> {
        val jsonParser = JsonParser()
        val jsonElements = jsonParser.parse(s).asJsonArray //获取JsonArray对象
        val beans: MutableList<T> = ArrayList()
        for (bean in jsonElements) {
            val bean1: T? = jsonToResult(classz, bean) //解析
            if (bean1!=null){
                beans.add(bean1)
            }
        }
        return beans
    }

    fun <T> jsonToResult(class1: Class<T>, s: JsonElement?): T? {
        val result: T?
        result = try {
            gsonObject.fromJson(s, class1)
        } catch (e: Exception) {
            null
        }
        return result
    }

    fun <T> fromLocalJson(json: String?, typeOfT: Type?): T {
        return gsonObject.fromJson(json, typeOfT)
    }
}